import os.path

import yaml
from litemall_0805.frame.utils.logger import logger


def repeat_click(by, locate=None, max_clicks=5):
    def __inner(driver):
        actual_clicks = 1
        while actual_clicks < max_clicks:
            try:
                if locate:
                    driver.find_element(by, locate).click()
                    logger.info(f"第{actual_clicks}次点击{locate}成功")
                    return True
                else:
                    driver.find_element(*by).click()
                    logger.info(f"第{actual_clicks}次点击{by}成功")
                    return True
            except Exception as e:
                logger.info(f"第{actual_clicks}次点击{locate}失败")
                actual_clicks += 1
        logger.info(f"达到最大点击次数{max_clicks}，依然点击失败")
        raise e
    return __inner


def repeat_clicks(func):
    max_clicks = 5

    def __inner(*args, **kwargs):
        actual_clicks = 1
        logger.info(f"第{actual_clicks}次点击")
        while actual_clicks < max_clicks:
            try:
                func()
                logger.info(f"第{actual_clicks}次点击成功")
                return True
            except Exception:
                logger.info(f"第{actual_clicks}次点击失败")
                actual_clicks += 1
        logger.info(f"达到最大点击次数{max_clicks}，依然点击失败")

    return __inner


def get_frame_root_path():
        return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

def get_yamldata(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        data = yaml.safe_load(f)
    return data